package com.cash.lemoloan.statisticlib.Utils;

import static android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_OTHER;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
import static android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE;
import static android.provider.ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME;
import static android.provider.ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME;
import static android.provider.ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME;
import static android.provider.ContactsContract.Data.CONTENT_URI;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.cash.lemoloan.statisticlib.StatisticApplication;
import com.cash.lemoloan.statisticlib.model.StatisticContactsInfo;

import java.util.ArrayList;
import java.util.List;

public class ContactsUtil {
    private static ContactsUtil contactsUtil;
    public static ContactsUtil getInstance() {
        if (contactsUtil == null) {
            synchronized (PreferencesUtil.class) {
                if (contactsUtil == null) {
                    contactsUtil = new ContactsUtil();
                }
            }
        }
        return contactsUtil;
    }

    /**
     *
     * @return
     */
    public int getContactsCount(){
        ContentResolver resolver = StatisticApplication.getInstance().getContentResolver();
        if(resolver == null){
            return -1;
        }
        Cursor cursor = resolver.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Data.RAW_CONTACT_ID);
        int count = (cursor==null?-1:cursor.getCount());
        if (cursor != null) {
            cursor.close();
        }
        return count;
    }

    public synchronized static List<StatisticContactsInfo> getContactsInfo(){
        Cursor cursor = null;
        List<StatisticContactsInfo> contactsInfos = new ArrayList<>();
        try {

            cursor = StatisticApplication.getInstance()
                    .getContentResolver()
                    .query(CONTENT_URI, null, null, null, ContactsContract.Data.RAW_CONTACT_ID);
            if (cursor == null) {
                return null;
            }

//            int allCount = getAllCount(cursor);
            boolean moveToFirst = cursor.moveToFirst();
            if(!moveToFirst){
                return null;
            }
            int currentNum = 1;

            @SuppressLint("Range") int oldId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
            StatisticContactsInfo contactsInfo = new StatisticContactsInfo();
            contactsInfo.setCtime(String.valueOf(System.currentTimeMillis()));
            contactsInfo.setContactId(currentNum);
            contactsInfos.add(contactsInfo);
            ++currentNum;
            getData(cursor, contactsInfo);
            while (cursor.moveToNext()){
                @SuppressLint("Range") int contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
                if(oldId != contactId){
                    contactsInfo = new StatisticContactsInfo();
                    contactsInfo.setCtime(String.valueOf(System.currentTimeMillis()));
                    contactsInfo.setContactId(currentNum);
                    contactsInfos.add(contactsInfo);
                    oldId = contactId;
                    ++currentNum;
                }
                getData(cursor, contactsInfo);
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null) {
                try {
                    cursor.close();
                }catch (Exception e){}
            }
            return contactsInfos;
        }
    }

//    public static int getAllCount(Cursor cursor) {
//        int allCount = 0;
//        cursor.moveToFirst();
//        int oldId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
//        ++allCount;
//        while (cursor.moveToNext()) {
//            int contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
//            //会有多个contactId进行查询，防止重复
//            if (oldId != contactId) {
//                oldId = contactId;
//                ++allCount;
//            }
//        }
//
//        return allCount;
//    }

    private static void getData(Cursor cursor, StatisticContactsInfo contactsInfo) {
        // 取得mimeType类型
        @SuppressLint("Range") String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
        // 获取电话信息
        if (mimeType == null) {
            return;
        }
        switch (mimeType) {
            case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
                getPhone(cursor, contactsInfo);
                break;
            case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
                getContactName(cursor, contactsInfo);
                break;
            default:
                break;
        }
    }

    private static void getPhone(Cursor cursor, StatisticContactsInfo contactsInfo) {
        // 取出电话类型
        @SuppressLint("Range") int phoneType = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
        switch(phoneType) {
            // 手机
            case TYPE_MOBILE:
                @SuppressLint("Range") String mobile = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), mobile));
                break;
            // 住宅电话
            case TYPE_HOME:
                @SuppressLint("Range") String homeNum = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), homeNum));
                break;
            // 单位电话
            case TYPE_WORK:
                @SuppressLint("Range") String jobNum = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), jobNum));
                break;
            // 单位传真
            case TYPE_FAX_WORK:
                @SuppressLint("Range") String workFax = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), workFax));
                break;
            // 住宅传真
            case TYPE_FAX_HOME:
                @SuppressLint("Range") String homeFax = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), homeFax));
                break;
            // 公司总机
            case TYPE_COMPANY_MAIN:
                @SuppressLint("Range") String jobTel = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), jobTel));
                break;
            // 单位手机
            case TYPE_WORK_MOBILE:
                @SuppressLint("Range") String jobMobile = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), jobMobile));
                break;
            //其他号码
            case TYPE_OTHER:
                @SuppressLint("Range") String otherMobile = cursor.getString(cursor.getColumnIndex(NUMBER));
                contactsInfo.setPhone(addComma(contactsInfo.getPhone(), otherMobile));
                break;
            default:
                break;
        }
    }

    private static void getContactName(Cursor cursor, StatisticContactsInfo contactsInfo) {
        // 获得通讯录中联系人的名字
        @SuppressLint("Range") String displayName = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
        @SuppressLint("Range") String lastModify = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP));
        if (TextUtils.isEmpty(displayName)) {
            @SuppressLint("Range") String firstName = cursor.getString(cursor.getColumnIndex(FAMILY_NAME));
            @SuppressLint("Range") String lastName = cursor.getString(cursor.getColumnIndex(GIVEN_NAME));

            String fullName = firstName + lastName;
            if (!TextUtils.isEmpty(fullName)) {
                contactsInfo.setName(fullName);
            }
        } else {
            contactsInfo.setName(displayName);
            contactsInfo.setlastModified(lastModify);
        }
    }

    private static String addComma(String oldStr, String newStr) {
        if (!TextUtils.isEmpty(oldStr) && !TextUtils.isEmpty(newStr)) {
            newStr = oldStr + "," + newStr;
        }
        return newStr;
    }
}
